<template>
     <div id="app" class="login_container" @keydown.enter="login">
          <!-- 登录卡片 -->
          <div class="login_wrapper">
               <el-form
                    class="login_form"
                    :model="loginForm"
                    :rules="rules"
                    ref="loginForms"
               >
                    <div class="login_header">
                         <div class="logo-container">
                              <img
                                   :src="setting.logo"
                                   alt="Logo"
                                   class="logo-image"
                              />
                         </div>
                         <h1 class="login-title">欢迎登录</h1>
                         <h2 class="system-name">{{ setting.title }}</h2>
                    </div>
                    <el-form-item prop="username">
                         <el-input
                              :prefix-icon="User"
                              v-model="loginForm.username"
                              clearable
                         ></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                         <el-input
                              type="password"
                              :prefix-icon="Lock"
                              v-model="loginForm.password"
                              show-password
                              clearable
                         ></el-input>
                    </el-form-item>
                    <el-form-item prop="verifycode">
                         <el-input
                              v-model="loginForm.verifycode"
                              autocomplete="off"
                              :maxlength="4"
                              placeholder="请输入验证码"
                         >
                              <template #prepend style="padding: 0 !important">
                                   <ImgVerify
                                        @click="refashCode"
                                        v-if="ImgVerifyShow"
                                        :width="150"
                                        :height="40"
                                        :pool="pollCode"
                                   ></ImgVerify>
                              </template>
                              <template #suffix>
                                   <el-icon
                                        color="green"
                                        v-if="
                                             loginForm.verifycode &&
                                             isVerifycode
                                        "
                                   >
                                        <circle-check />
                                   </el-icon>
                                   <el-icon
                                        color="red"
                                        v-if="
                                             loginForm.verifycode &&
                                             !isVerifycode
                                        "
                                   >
                                        <circle-close />
                                   </el-icon>
                              </template>
                         </el-input>
                    </el-form-item>
                    <el-form-item>
                         <el-button
                              :loading="loading"
                              class="login_btn animate-hoverLift"
                              type="primary"
                              size="default"
                              @click="login"
                         >
                              登录
                         </el-button>
                    </el-form-item>
               </el-form>

               <!-- 页脚信息 -->
               <div class="login_footer">
                    <p>© {{ new Date().getFullYear() }} {{ setting.title }}</p>
               </div>
          </div>
     </div>
</template>

<script setup lang="ts">
import JSEncrypt from 'jsencrypt'
import { hex_md5 } from '@/utils/encrypt'
// @ts-ignore
import { User, Lock } from '@element-plus/icons-vue'
// import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
// @ts-ignore
import ImgVerify from '@/components/ImgVerify/index.vue'
import setting from '../../setting'

// 粒子动画效果
onMounted(() => {})
const publicKey = `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjtu1w4s79b6tN8NmYxHh0oNmW+CmAh1MpSJaZbkI2Un/3TMqQx3m2fvHnqYPRCNAILn4oueWfYNJjPtnKMH2XXbUWq/li1/uqwr2zUkey1pWf7UlDKKP5gUMdCmxOFGHcG98BZIF46AsLlEvOrFDTy3pnDWv6h7thsLi7CmqlFTye0XvesTsxwELvmV8BShEo3PXNPpFbnoT9R7FTsi7cGRE8uISyavCzImRBa4lVqdK3Z33V4/CRjbtDL2W1hxAJm25coODUbI1AOA2LMjs8EN7zKUfRNA+mCAtSIlmG5KvIrlAYcBEBlFcdbZmsFVpvCCZoeXrETaQ9ZEWfQbMMQIDAQAB`
let useStore = useUserStore()
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()
//定义变量控制按钮加载效果
let loading = ref(false)
// 判断是否开发环境
const isDev = process.env.NODE_ENV === 'development'
//收集账号与密码的数据
let loginForm = reactive({
     username: isDev ? 'sunnan' : '',
     password: isDev ? 'crdchys*123' : '',
     verifycode: '',
})
const isVerifycode = computed(() => {
     //判断验证码是否正确
     return pollCode.value == loginForm.verifycode
})
const ImgVerifyShow = ref(true)
const pollCode = ref<number | string>('')
onMounted(async () => {
     refashCode()
})
const refashCode = async () => {
     useStore.getVerifyCode()
     pollCode.value = useStore.verifyCodes.toString()
     ImgVerifyShow.value = false
     nextTick(() => {
          ImgVerifyShow.value = true
     })
}
//获取el-form组件
let loginForms = ref()
//登录按钮回调
const login = () => {
     console.log('login')
     if (!isVerifycode.value) {
          return ElNotification({
               type: 'error',
               message: '验证码错误',
               title: '验证码错误',
          })
     }
     loginForms.value &&
          loginForms.value.validate(async (valid: any) => {
               if (valid) {
                    try {
                         loading.value = true
                         //保证登录成功
                         const encrypt = new JSEncrypt()
                         encrypt.setPublicKey(publicKey)
                         let obj: any = {
                              username: loginForm.username,
                              // password: md5(loginForm.password),
                              // password: encrypt.encrypt(loginForm.password),
                              password: loginForm.password,
                              // client_secret: '1a2b3c4d5e6f7890',
                              // client_id: 'china_rail_way',
                              // grant_type: 'password',
                         }
                         await useStore.userLogin(obj)
                         //编程式导航跳转到展示数据首页
                         //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
                         let redirect: any = $route.query.redirect || ''
                         console.log('redirect', redirect)
                         $router.push({ path: redirect || '/mapPages' })
                         //登录成功提示信息
                         // ElNotification({
                         //      type: 'success',
                         //      message: '欢迎回来',
                         //      title: `HI,${getTime()}好`,
                         // })
                         //登录成功加载效果也消失
                         loading.value = false
                    } catch (error) {
                         refashCode()
                         //登录失败加载效果消息
                         loading.value = false
                         //登录失败的提示信息
                         ElNotification({
                              type: 'error',
                              message: (error as Error).message,
                         })
                    }
               } else {
                    console.log('error submit!')
               }
          })
}
const md5 = (pwd: string) => {
     return hex_md5(hex_md5(pwd)).substring(0, 18)
}
// @ts-ignore
//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
     if (value.length >= 2) {
          callback()
     } else {
          callback(new Error('账号长度至少三位'))
     }
}
// @ts-ignore
const validatorPassword = (rule: any, value: any, callback: any) => {
     if (value.length >= 6) {
          callback()
     } else {
          callback(new Error('密码长度至少六位'))
     }
}

//定义表单校验需要配置对象
const rules = {
     username: [{ trigger: 'change', validator: validatorUserName }],
     password: [{ trigger: 'change', validator: validatorPassword }],
     verifycode: [
          {
               required: true,
               min: 4,
               max: 4,
               message: '请输入验证码,长度为4位',
               trigger: 'change',
          },
     ],
}
</script>
<style scoped lang="scss">
// 登录容器样式
.login_container {
     width: 100vw;
     height: 100vh;
     display: flex;
     justify-content: center;
     align-items: center;
     background: url('@/assets/images/login/login_bg2.png') no-repeat;
     background-size: 100% 100%;
     overflow: hidden;
     position: relative;

     // 登录包装器
     .login_wrapper {
          display: flex;
          flex-direction: column;
          align-items: center;
          z-index: 10;

          // 登录表单样式
          .login_form {
               width: 420px;
               // background-color: white;
               padding: 45px;
               border-radius: 20px;
               box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
               position: relative;
               overflow: hidden;
               backdrop-filter: blur(16px);
               animation: scaleIn 0.5s ease-out;

               // 登录头部样式
               .login_header {
                    text-align: center;
                    margin-bottom: 30px;

                    // Logo容器样式
                    .logo-container {
                         display: flex;
                         justify-content: center;
                         margin-bottom: 20px;

                         // Logo图片样式
                         .logo-image {
                              width: 80px;
                              height: 80px;
                              border-radius: 50%;
                              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                              transition: all 0.3s ease;

                              &:hover {
                                   transform: scale(1.05);
                                   box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
                              }
                         }
                    }

                    // 登录标题样式
                    .login-title {
                         font-size: 28px;
                         font-weight: 600;
                         // color: #303133;
                         color: #fff;
                         margin: 0 0 10px 0;
                         background: linear-gradient(90deg, #409eff, #67c23a);
                         -webkit-background-clip: text;
                         background-clip: text;
                         color: transparent;
                    }

                    // 系统名称样式
                    .system-name {
                         font-size: 18px;
                         color: #fff;
                         margin: 0;
                    }
               }

               // 按钮样式
               .login_btn {
                    width: 100%;
                    height: 45px;
                    // background: linear-gradient(90deg, #409eff, #67c23a);
                    border: none;
                    font-size: 16px;
                    font-weight: 500;
                    border-radius: 12px;
                    transition: all 0.3s ease;
                    position: relative;
                    overflow: hidden;

                    &::before {
                         content: '';
                         position: absolute;
                         top: 50%;
                         left: 50%;
                         width: 0;
                         height: 0;
                         // background: rgba(255, 255, 255, 0.3);
                         border-radius: 50%;
                         transform: translate(-50%, -50%);
                         transition:
                              width 0.6s,
                              height 0.6s;
                    }

                    &:active {
                         transform: translateY(0);
                    }
               }
          }

          // 页脚样式
          .login_footer {
               margin-top: 20px;
               text-align: center;
               color: white;
               opacity: 0.8;
               font-size: 12px;
          }
     }
}

// Element Plus 输入框样式深度定制
::v-deep {
     .el-input {
          border-radius: 12px;
          height: 45px;
          margin-bottom: 24px;
          transition: all 0.3s ease;
     }

     .el-input__wrapper {
          // border-radius: 12px;
          transition: all 0.3s ease;
          border-color: #dcdfe6;

          &:hover {
               border-color: #409eff;
               // box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }

          &.is-focus {
               border-color: #409eff;
               // box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
     }

     .el-input__inner {
          // border-radius: 12px;
          height: 45px;
          font-size: 14px;
     }

     .el-input-group__append {
          padding: 0 15px;
          // border-radius: 0 12px 12px 0;
     }

     .el-input-group__prepend {
          padding: 0 15px;
          border-radius: 12px 0 0 12px;
     }
}

// 悬停提升效果
.animate-hoverLift {
     animation: hoverLift 0.3s ease-out forwards;
     animation-play-state: paused;

     &:hover {
          animation-play-state: running;
     }
}

// 响应式设计
@media (max-width: 480px) {
     .login_container {
          .login_wrapper {
               .login_form {
                    width: 90%;
                    padding: 30px 25px;

                    .login_header {
                         .logo-container {
                              .logo-image {
                                   width: 60px;
                                   height: 60px;
                              }
                         }

                         .login-title {
                              font-size: 24px;
                         }
                    }
               }
          }
     }
}
</style>
